package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.FreemarkUtil;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.ISceneService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//区域资源的控制器
@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext ctx;
    @Autowired
    private ISceneService sceneService;

    /*
    获取所有的区域
    资源:/regions
    动作:GET
    参数:
     */
    @GetMapping
    public Object list(Integer state) {
        return regionService.list(state);
    }

    /*
    获取某个区域推荐的攻略
    资源:/regions/{strategyId}/strategies
    动作:GET
    参数:state=2&currentPage=x
     */
    @GetMapping(value = "/{regionId}/strategies", produces = "text/html;charset=UTF-8")
    public void queryStrategies(StrategyQueryObject qo, HttpServletResponse resp) throws Exception {
        String dir = ctx.getRealPath("/template");
        Map<String, Object> map = new HashMap<>();
        map.put("id", qo.getRegionId()); //当前区域的id

        //1:全部数据
        qo.setState(-1L);
        qo.setPageSize(4);
        PageInfo<Strategy> pageInfo = strategyService.query(qo);
        //如果是翻页操作则直接返回数据即可,不需要再次出现精品推荐
        if (qo.getCurrentPage() != 1) {
            map.put("info", pageInfo);
            FreemarkUtil.writeData(dir, "classify.ftl", map, resp.getWriter());
            return;
        }

        //2:精品推荐
        qo.setState(2L);
        qo.setPageSize(0);
        List<Strategy> commends = strategyService.query(qo).getList();

        map.put("info", pageInfo);
        map.put("commends", commends);
        FreemarkUtil.writeData(dir, "strategyContent.ftl", map, resp.getWriter());
    }


   /*
    获取所有地区的景点
    资源:/regions/{id}/scenes
    动作:GET
    参数*/

    @GetMapping("/{id}/scenes")
    public Object listScenesBy(@PathVariable Long id) {
        return sceneService.listScenesByRegionId(id);
    }
}
